<?php

namespace App\Repository\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

use Illuminate\Support\Facades\DB;

/**
 * Class Shop.
 *
 * @package namespace App\Repository\Models;
 */
class Shop extends Model implements Transformable
{
    use TransformableTrait;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    const CREATED_AT = 'sp_created';
    protected $table = 'shop';

    protected $primaryKey = 'sp_id';

    protected $fillable = ['sp_id', 'sp_name', 'sp_logo', 'sp_cmp_id','sp_uid', 'sp_intro', 'sp_status','sp_templete', 'sp_type_id', 'sp_score', 'sp_level', 'sp_title', 'key_words', 'description',
        'order_time', 'receipt_time', 'return_time', 'stock_time', 'good_comment_count', 'medium_comment_count', 'negative_comment_count',
        'product_comment_score', 'product_comment_count', 'seller_comment_score', 'seller_comment_count', 'logistics_comment_score', 'logistics_comment_count','is_recommend'
    ];
    protected $appends = ['products_num'];

    public function getProductsNumAttribute(){
        $countAll = DB::table('products')
            ->select('is_for_sale', DB::raw('count(*) as total'))
            ->where('shop_id',$this->sp_id)
            ->groupBy('is_for_sale')
            ->get();
        $all = 0;
        $is_for_sale = 0;
        foreach ($countAll as $count){
            $all += $count->total;
            if ($count->is_for_sale==1){
                $is_for_sale += $count->total;
            }
        }
        return ['all'=>$all,'onsale'=>$is_for_sale];
    }
    public function company()
    {
        return $this->hasOne(Company::class, 'id', 'sp_cmp_id');
    }
    
    public function companyMaterial()
    {
        return $this->hasOne(CompanyMaterial::class, 'company_id', 'sp_cmp_id');
    }

    public function shopLevel()
    {
        return $this->hasOne(ShopLevel::class, 'lv_id', 'sp_level');
    }

    public function product(){
        return $this->hasMany(Products::class,'shop_id','sp_id');
    }

    public function user(){
        return $this->hasOne(User::class,'id','sp_uid');
    }
    public function shopBanners(){
        return $this->hasMany(ShopBanners::class,'shop_id','sp_id');
    }


}
